#!/usr/bin/env python
#coding:utf8

import sys
import os

curdir = os.path.dirname(__file__)
sys.path.append(os.path.join(curdir, 'crc'))

import crc8
import crc32

crc32.init_tables(0xedb88320)

def hex_crc8(string):
    hash = crc8.crc8()
    hash.update(string)
    crc = hash.hexdigest()
    return str(crc).upper()

def hex_crc32(string):
    bytes = tuple(map(ord, string))
    crc = crc32.calc(bytes)
    #crc = hex(crc)[2:10]
    crc = ('%08X' % crc)
    return str(crc).upper()

# function 路径转换为CRC路径
# test file[/resource/bigbg/timesummon/selectsummon_call_bg_25.jpg] => [\E2\A5\DB\742F7D4C].
# name 路径名称
def make_crc_path(name):
    s = name.replace('\\', '/')
    names = s.split('/')
    _len = len(names)
    path = ''

    if _len < 2:
        return name
    
    for i in range(_len):
        n = names[i]
        crc = n
        isnull = (n == "")
        first = (i == 0)
        second = (i == 1)
        end = (i == (_len - 1))
        sep = "/"
        if end:
            sep = ""

        if first or second or isnull:
            if n == "" or n == "src" or n == "res" or n == ".":
				path = path + crc + sep
				continue

        if end:
            file_name = names[i]
            file_names = file_name.split('.')
            if len(file_names) == 1:
                crc = hex_crc32(file_names[0])
            if len(file_names) == 2:
                crc = hex_crc32(file_names[0])
                crc = '%s.%s' % (crc, file_names[1])
        else:
            crc = hex_crc32(names[i])
            
        path = path + crc + sep

    return path